import { CoordinateSystem } from '@/core/CoordinateSystem';
import { XYAxis } from '@/core/XYAxis';
import GUI from "lil-gui";
import { Circle, Group, Line, Rect } from 'zrender';




export async function main(dom: HTMLDivElement, menu: GUI) {
  const cs = new CoordinateSystem(dom);
  (window as any).cs = cs

  new XYAxis(cs)

  const rect = new Rect({
    silent: true,
    shape: {
      x: 0,
      y: 0,
      width: 2,
      height: 2
    },
    style: {
      fill: '#00ffff',
      opacity: 0.1
    }
  })

  cs.root.add(rect)

  cs.zoomTo(rect)


  const a = new Circle({
    silent: true,
    x: 0,
    y: 2,
    z: 2,
    globalScaleRatio: 0,
    shape: {
      r: 5,
    },
    style: {
      fill: "#dd960f",
    }
  })

  cs.root.add(a)

  const b = new Circle({
    silent: true,
    x: 0,
    y: 0,
    z: 2,
    globalScaleRatio: 0,
    shape: {
      r: 5,
    },
    style: {
      fill: "#b2ff00",
    }
  })

  cs.root.add(b)

  const m = new Circle({
    silent: true,
    x: 0,
    y: 1,
    z: 2,
    globalScaleRatio: 0,
    shape: {
      r: 5,
    },
    style: {
      fill: "#2346cd",
    }
  })

  cs.root.add(m)


  const ab = new Line({
    silent: true,
    z: 1,
    shape: {
      y1: 2,
    },
    style: {
      stroke: '#e5d716',
      strokeNoScale: true
    }
  })

  cs.root.add(ab)

  const root = new Group()
  cs.root.add(root)

  let anim = 0
  let percent = 0

  function frame() {
    percent += 0.004

    const step = Math.floor(percent)
    const p = percent - step

    switch (step) {
      case 0:
        a.attr({
          x: 0,
          y: 2 * (1 - p)
        })
        b.attr({
          x: Math.sqrt(8 * p - 4 * p * p),
          y: 0
        })

        break;
      case 1:
        a.attr({
          x: 2 * p,
          y: 0
        })
        b.attr({
          x: 2,
          y: Math.sqrt(8 * p - 4 * p * p),
        })
        break;
      case 2:
        a.attr({
          x: 2,
          y: 2 * p,
        })
        b.attr({
          x: 2 - Math.sqrt(8 * p - 4 * p * p),
          y: 2,
        })
        break;
      case 3:
        a.attr({
          x: 2 * (1 - p),
          y: 2
        })
        b.attr({
          x: 0,
          y: 2 - Math.sqrt(8 * p - 4 * p * p),
        })
        break
    }

    m.attr({
      x: (a.x + b.x) / 2,
      y: (a.y + b.y) / 2,
    })
    ab.attr({
      shape: {
        x1: a.x,
        x2: b.x,
        y1: a.y,
        y2: b.y,
      }
    })

    root.add(new Circle({
      silent: true,
      x: m.x,
      y: m.y,
      z: 2,
      globalScaleRatio: 0,
      shape: {
        r: 2,
      },
      style: {
        fill: "#475ed3",
      }
    }))

    if (percent < 4) {
      anim = requestAnimationFrame(frame)
    } else {
      anim = 0
    }
  }

  menu.add({
    开始运动() {
      if (!anim) {
        percent = 0
        root.removeAll()
        anim = requestAnimationFrame(frame)
      }
    }
  }, '开始运动')

  return () => {
    cs.destroy()
  }
}